require 'family_tree_api/search/event'

module FamilyTreeApi
  module Search

    class Person
      attr_accessor :ref, :name, :gender, :events
      
      def initialize
        @events = []
      end
      
      def birth
        @birth ||= @events.select{|e| e.type == "Birth"}.first
        @birth
      end
      
      def marriage
        @marriage ||= @events.select{|e| e.type == "Marriage"}.first
        @marriage
      end
      
      def death
        @death ||= @events.select{|e| e.type == "Death"}.first
        @death
      end

      def parse_attributes p_element
        @ref = p_element.attributes["ref"]
        full_text_element = p_element.find_first("fs:name/fs:form/fs:fullText",NS)
        @name = full_text_element.content if full_text_element
        p_element.children.each do |e|
          case e.name
          when 'gender'
            @gender = e.content
          when 'events'
            @events = Event.parse(e)
          end
        end
      end

      def self.parse(p_element)
        person = self.new
        person.parse_attributes p_element
        person
      end

    end

    class Parent < Person
      attr_accessor :role

      def parse_attributes parent_element
        super parent_element
        @role = parent_element.attributes["role"]
      end

    end

  end
end